package com.alstudio.event;

import java.util.ArrayList;
import java.util.List;

 /**
  * PendingALEvent用于构造事件，并将事件加入到事件队列中。PendingALEvent中的事件
  * @author alonso lee
  *
  */
public class PendingALEvent {
    private final static List<PendingALEvent> pendingALEventPool = new ArrayList<PendingALEvent>();
    public Object event;
    public SubscriptionObject subscriptionObject;
    PendingALEvent next;

    
    private PendingALEvent(Object event, SubscriptionObject subscriptionObject) {
        this.event = event;
        this.subscriptionObject = subscriptionObject;
        this.next = null;
    }

    /**
     * 创建
     * @param subscriptionObject
     * @param event
     * @return
     */
    static PendingALEvent obtainPendingPost(SubscriptionObject subscriptionObject, Object event) {
    	//首先锁住事件队列，查看队列中是否有事件
        synchronized (pendingALEventPool) {
            int size = pendingALEventPool.size();
            if (size > 0) {
                PendingALEvent pendingALEvent = pendingALEventPool.remove(size - 1);
                pendingALEvent.event = event;
                pendingALEvent.subscriptionObject = subscriptionObject;
                pendingALEvent.next = null;
                return pendingALEvent;
            }
        }
        //队列中木有事件，直接创建一个新的事件对象
        return new PendingALEvent(event, subscriptionObject);
    }

    static void releasePendingPost(PendingALEvent pendingALEvent) {
        pendingALEvent.event = null;
        pendingALEvent.subscriptionObject = null;
        pendingALEvent.next = null;
        synchronized (pendingALEventPool) {
            // Don't let the pool grow indefinitely
            if (pendingALEventPool.size() < 10000) {
                pendingALEventPool.add(pendingALEvent);
            }
        }
    }

}
